package com.my.goodsmanage.controller;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.my.goodsmanage.entity.*;
import com.my.goodsmanage.service.GoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author 徐佳辉
 * @date 2020/8/4 19:53
 */
@Controller
@RequestMapping("/goods")
@Slf4j
@CrossOrigin
public class GoodsController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private PictureController pictureController;


    /**
     * 查询信息
     *
     * @param session
     * @return
     */
    @PostMapping("/info")
    @ResponseBody
    public R info(HttpSession session) throws ParseException {
        User user = (User) session.getAttribute("user");
        if (user == null) {

            return R.error("请登录。");
        }
        Integer userId = user.getUserId();
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<Goods> list = goodsService.list(wrapper);
        List<GoodsStr> strList = new ArrayList<>();
        if (CollectionUtils.isEmpty(list)) {
            //kong

            return R.error("无数据");
        } else {
            //非空
            SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (Goods goods : list) {
                Date createTime = goods.getCreateTime();
                Date updateTime = goods.getUpdateTime();
                String create = f.format(createTime);
                String update = f.format(updateTime);
                GoodsStr goodsStr = new GoodsStr();
                goodsStr.setGoodId(goods.getGoodId());
                goodsStr.setUserId(goods.getUserId());
                goodsStr.setGoodName(goods.getGoodName());
                goodsStr.setQuantity(goods.getQuantity());
                goodsStr.setGoodPlace(goods.getGoodPlace());
                goodsStr.setDetail(goods.getDetail());
                goodsStr.setCreateTime(create);
                goodsStr.setUpdateTime(update);
                strList.add(goodsStr);
            }

            return R.success(strList);
        }

    }

    /**
     * 获取用户名
     *
     * @param session
     * @return
     */
    @PostMapping("/name")
    @ResponseBody
    public R username(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return R.error("请登录");
        }
        return R.success(user);
    }

    /**
     * 添加或更新信息
     *
     * @param session
     * @return
     */
    @PostMapping("/insert")
    @ResponseBody
    public R insert(HttpSession session, Goods goods) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return R.error("请登录才能添加");
        }

        Integer userId = user.getUserId();
        goods.setUserId(userId);
        log.info(goods.toString());
        if (goods.getGoodId() != null) {

            goods.setUpdateTime(new Date());
            boolean b = goodsService.updateById(goods);
            if (b) {
                return R.success("更新成功");
            } else {
                return R.error("更新失败");
            }

        } else {
            goods.setCreateTime(new Date());
            goods.setUpdateTime(new Date());
            boolean save = goodsService.save(goods);
            if (save) {
                return R.success("添加成功");
            } else {
                return R.error("添加失败");
            }
        }


    }

    /**
     * 分页数据
     *code 0 为成功
     * @return
     */
    @PostMapping("/page")
    @ResponseBody
    public PageR page(@RequestParam int page, @RequestParam int limit, HttpSession session, String name) {
        User user = (User) session.getAttribute("user");
        log.info("page:[{}],size:[{}]", page, limit);
        PageR pageR = new PageR();


        Page<Goods> goodsPage = new Page<>(page, limit);
        goodsService.pageListCondition(goodsPage, user.getUserId(), name);

        log.info("pagegoods:[{}],size:[{}],total:[{}]", goodsPage.getCurrent(), goodsPage.getSize(), goodsPage.getTotal());
        pageR.setCode(0);
        pageR.setCount(goodsPage.getTotal());
        pageR.setSuccess(true);
        pageR.setMsg("成功");
        pageR.setData(goodsPage.getRecords());

        return pageR;
    }

    /**
     * 根据goodid删除物品
     *
     * @param goodId
     * @return
     */
    @PostMapping("/delete/{goodId}")
    @ResponseBody
    public R delete(@PathVariable Integer goodId) {
        boolean b = goodsService.removeById(goodId);
        log.info("goodId:[{}]",goodId);
        if (b) {

            boolean b1 = pictureController.deleteFileOnTwo(goodId);
            return b1 ? R.success("删除成功") : R.error("删除图片失败");

        } else {
            return R.error("删除失败");
        }
    }

    @GetMapping("/get/{goodId}")
    @ResponseBody
    public R getGoodById(@PathVariable Integer goodId) {
        Goods good = goodsService.getById(goodId);
        if (good != null) {
            return R.success(good);
        } else {
            return R.error("没有查到此物");
        }
    }

    @PostMapping("/deletes")
    @ResponseBody
    public R deletes(@RequestBody List<Goods> data) {
        log.info("data size:[{}]", data.size());
        List<Integer> ids = new ArrayList<>();
        for (Goods datum : data) {
            ids.add(datum.getGoodId());
        }
        boolean b = goodsService.removeByIds(ids);
        if (b) {
            return R.success("删除成功");
        } else {
            return R.error("删除失败");
        }
    }

}
